package com.y3k.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Locale;

import org.apache.log4j.Logger;

import com.y3k.model.Datasource;

public class ConnectionHelper {

	public static final Logger log = Logger.getLogger(ConnectionHelper.class);

	private static ConnectionHelper instance;

	private Connection conn;

	private ConnectionHelper() {
		try {
			Locale.setDefault(Locale.ENGLISH);
			Datasource datasource = ConfigurationUtil.getDefaultDataSource();

/*			log.info("Driver [" + datasource.getDriver() + "]");
			log.info("Username [" + datasource.getUsername() + "]");
			log.info("Password [" + datasource.getPassword() + "]");*/

			Class.forName(datasource.getDriver());
			
/*			this.conn = DriverManager.getConnection(datasource.getSource(), datasource.getUsername(), datasource.getPassword());
			this.conn.setAutoCommit(false);*/
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	public static Connection getConnection() throws SQLException {
		// Si no existe la instacia de connectionHelper, la crea
		if (instance == null) {
			instance = new ConnectionHelper();
		}
		
		// Si la conexion esta cerrada, crearla
		if (instance.conn == null || instance.conn.isClosed()){
			instance.conn = createConnection();
		}
		
		return instance.conn;
	}
	
	private static Connection createConnection () throws SQLException {
		try {
				Locale.setDefault(Locale.ENGLISH);
				Datasource datasource = ConfigurationUtil.getDefaultDataSource();
				
				log.info("Driver [" + datasource.getDriver() + "]");
				log.info("Username [" + datasource.getUsername() + "]");
				log.info("Password [" + datasource.getPassword() + "]");
				
				Connection conn = DriverManager.getConnection(datasource.getSource(), datasource.getUsername(), datasource.getPassword());
				conn.setAutoCommit(false);			
			
				return conn;
		} catch (SQLException e) {
			throw e;
		}
	}
	
}